import SparkMD5 from 'spark-md5'
import { defineStore } from 'pinia';
// import {getFileUpload} from "@/api/system/fileUpload";
import axios from "axios";

const msgInfo = {type: null, uid: null, status: 0, md5: '', progress: 0}
const msgType = {STATUS: 1, PROGRESS: 2}
let isDelete = false
let workStatus = 0;
let sysFileUpload = {}
let token = null
let localFile = null //需要上传的文件
// let chunkFile

onmessage = function (e) {
    console.log("进入worker");
    if (e.data.cmd === 1) {
        token = e.data.token
        msgInfo.uid = e.data.uid
        sysFileUpload.fileSize = e.data.file.size
        localFile = e.data.file
        computeMD5(e.data.file)
    } else if (e.data.cmd === 2) {
        isDelete = true
        if (workStatus === 4 || workStatus === 5) {
            sendStatus(6)
        }
    }
}

function sendStatus(status, md5 = '',filePath='') {
    msgInfo.type = msgType.STATUS
    workStatus = status
    msgInfo.status = status;
    msgInfo.md5 = md5;//获取MD5
    msgInfo.filePath = filePath
    self.postMessage(msgInfo)
}

function sendProgress(progress) {
    msgInfo.type = msgType.PROGRESS
    msgInfo.progress = progress;//获取MD5
    self.postMessage(msgInfo)
}


function uploadFile() {
    console.log("uploadFile");
    //getFileUpload(sysFileUpload, token)
    axios.get(import.meta.env.VITE_APP_BASE_API + "/system/bigFileUpload/getFileInfo",
        {
            method: 'get',
            params: sysFileUpload,
            headers: {
                Authorization: "Bearer " + token,
            }
        }
    )
    .then(res => {
        sysFileUpload = res.data.data
        if (sysFileUpload.status === 1){
            sendStatus(4,sysFileUpload.md5,sysFileUpload.filePath)
            return
        }
        console.log("通过md5获取上传信息" + JSON.stringify(sysFileUpload));

        let chunkSize = 2097152 //2MB
        // let fileReader = new FileReader();
        // fileReader.onload = (e) => {
        //     console.log("发送数据" + JSON.stringify(chunkFile));
        //     const formData = new FormData();
        //     formData.append("chunkFile", chunkFile);
        //     formData.append("sysFileUpload", sysFileUpload);
        //     axios.post(import.meta.env.VITE_APP_BASE_API + "/system/bigFileUpload/uploadData",{chunkFile,sysFileUpload},{
        //         headers: {
        //             Authorization: "Bearer " + token
        //         }}).then(res =>{
        //         sysFileUpload=res.data;
        //         console.log("已上传长度:"+sysFileUpload.saveSize)
        //         sendProgress(Number((sysFileUpload.saveSize * 100 / sysFileUpload.fileSize).toFixed(2)))
        //         if(sysFileUpload.saveSize === localFile.size || sysFileUpload.status === 1){
        //             sendStatus(4)
        //             sendProgress(100)
        //         }else{
        //             loadNext()
        //         }
        //     }).catch(error =>{
        //         console.log(error)
        //     })
        // upLoadData(e.target.result,sysFileUpload,token).then(rest=>{//上传
        //     sysFileUpload = rest.data
        //     console.log("已上传长度:"+sysFileUpload.saveSize)
        //     sendProgress(Number((sysFileUpload.saveSize * 100 / sysFileUpload.fileSize).toFixed(2)))
        //     if(sysFileUpload.saveSize === localFile.size || sysFileUpload.status === 1){
        //         sendStatus(4)
        //         sendProgress(100)
        //     }else{
        //         loadNext()
        //     }
        // })
        // }
        let loadNext = () => {
            let start = sysFileUpload.saveSize === 0 ? 0 : sysFileUpload.saveSize - 1,
                end = ((start + chunkSize) >= localFile.size) ? localFile.size : start + chunkSize
            let chunkFile = localFile.slice(start, end);

            console.log("发送数据" + JSON.stringify(sysFileUpload));
            const json = JSON.stringify(sysFileUpload);
            // 将 json 字符串转化为 Blob 对象
            const blob = new Blob([json], {
                type: 'application/json',
            });
            const formData = new FormData();
            formData.append("chunkFile", chunkFile);
            formData.append("sysFileUpload", blob);
            axios.post(import.meta.env.VITE_APP_BASE_API + "/system/bigFileUpload/uploadData",
                formData,
                {
                    headers: {
                        "Content-Type": "multipart/form-data",
                        Authorization: "Bearer " + token,
                    }
                }
            ).then(res => {
                sysFileUpload = res.data;
                console.log("已上传长度:" + sysFileUpload.saveSize)
                sendProgress(Number((sysFileUpload.saveSize * 100 / sysFileUpload.fileSize).toFixed(2)))
                if (sysFileUpload.saveSize === localFile.size || sysFileUpload.status === 1) {
                    sendStatus(4,sysFileUpload.md5,sysFileUpload.filePath)
                    sendProgress(100)
                } else {
                     loadNext() //进行下一步处理
                }
            }).catch(error => {
                console.log(error)
            })


            //fileReader.readAsArrayBuffer(chunkFile);
        }
        loadNext();
    })
}

function computeMD5(file) {
    sendStatus(2)
    let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        chunkSize = 2097152, //2MB
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();

    //let time = new Date().getTime();
    fileReader.onload = (e) => {
        spark.append(e.target.result);
        currentChunk++;
        if (currentChunk < chunks) {
            sendProgress(Number((currentChunk * chunkSize * 100 / file.size).toFixed(2)))
            //console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk +1} / ${chunks}分片解析`);
            if (isDelete) {
                spark.destroy(); //释放缓存
                sendStatus(6)
            } else {
                loadNext();
            }
        } else {
            let md5 = spark.end() //得到md5
            sysFileUpload.checkCode = md5
            spark.destroy(); //释放缓存
            //console.log(`MD5计算完成：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${file.size} 用时：${new Date().getTime() - time} ms`);
            sendProgress(100)
            sendStatus(3, md5)
            uploadFile()
        }
    }
    fileReader.onerror = () => {
        spark.destroy(); //释放缓存
        sendStatus(5)
        console.warn('oops, something went wrong.');
    }
    let loadNext = () => {
        let start = currentChunk * chunkSize,
            end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    }
    loadNext();
}